/**
 *   ro.dandanciu.webgallery.services.impl.RegistrationRequestServicesImpl.java [WebGalleryBusiness]
 *   Copyright (C) Jul 19, 2008 - Dan Danciu
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place - Suite 330,
 *   Boston, MA 02111-1307, USA.
 */
package ro.dandanciu.webgallery.services.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import ro.dandanciu.webgallery.domainmodel.RegistrationRequest;
import ro.dandanciu.webgallery.domainmodel.User;
import ro.dandanciu.webgallery.domainmodel.utils.AccountStatus;
import ro.dandanciu.webgallery.domainmodel.utils.DbConstants;
import ro.dandanciu.webgallery.services.RegistrationRequestServices;
import ro.dandanciu.webgallery.util.email.framework.EmailFromTemplate;
import ro.dandanciu.webgallery.util.email.framework.exceptions.NoSuchEmailTemplateException;
import ro.dandanciu.webgallery.util.properties.PropertyReader;

/**
 *
 *
 * @author Dan Danciu
 */
@Transactional
public class RegistrationRequestServicesImpl extends AbstractServicesImpl
        implements RegistrationRequestServices {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger
            .getLogger(RegistrationRequestServicesImpl.class);

    private static final PropertyReader prApplication = new PropertyReader("application");
    /*
     * (non-Javadoc)
     *
     * @see ro.dandanciu.webgallery.services.RegistrationRequestServices#
     *      confirmRegistrationRequest(java.lang.String)
     */
    @Override
    public User confirmRegistrationRequest(final String code)
            throws RegistrationCodeInvalidException {

        final RegistrationRequest registrationRequest = getRegistrationRequestByCode(code);

        if (registrationRequest == null
                || !AccountStatus.REGISTRATION_REQUEST
                        .equals(registrationRequest.getUser().getStatus())) {
            throw new RegistrationCodeInvalidException();
        }

        final User user = registrationRequest.getUser();
        user.setStatus(AccountStatus.ENABLED);
        em.persist(user);

        em.remove(registrationRequest);

        return user;

    }

    /**
     * If there is exactly one registration request with this code we return the
     * registration request, otherwise we return null.
     *
     * @param code
     *            the code of the registration request.
     * @return a registration request if one exists with the given code or null
     *         otherwise.
     */
    private RegistrationRequest getRegistrationRequestByCode(final String code) {
        final Query query = em
                .createNamedQuery("RegistrationRequest.GetByCode");
        query.setParameter("code", code);
        final List<RegistrationRequest> list = query.getResultList();
        if (list.size() == 1) {
            return list.get(0);
        }
        return null;
    }

    /*
     * (non-Javadoc)
     *
     * @see ro.dandanciu.webgallery.services.RegistrationRequestServices#
     *      createRegistrationRequest(java.lang.String, java.lang.String)
     */
    @Override
    public void createRegistrationRequest(final String userId,
            final String email) {

        final User user = new User();
        user.setUserId(userId);
        user.setEmail(email);
        user.setStatus(AccountStatus.REGISTRATION_REQUEST);
        user.setUpdater("registraiton request creation");

        em.persist(user);

        final RegistrationRequest registrationRequest = new RegistrationRequest();
        registrationRequest.setUser(user);
        registrationRequest.setRequestDate(new Date());
        registrationRequest.setCode(generateRegistrationCode());

        em.persist(registrationRequest);

        sendEmailForRegistrationRequest(registrationRequest);
    }

    /**
     * Send the email containing the confirmation for this registration request.
     *
     * @param registrationRequest
     *            the registration request for which we want to send out the
     *            email with the confirmation code.
     */
    private void sendEmailForRegistrationRequest(
            final RegistrationRequest registrationRequest) {
        try {
            final List<String> email = new ArrayList<String>();
            email.add(registrationRequest.getUser().getEmail());
            final Map<String, String> params = new HashMap<String, String>();

            params.put("home.address", prApplication.getMessage("home.address"));
            params.put("confirmation.url", prApplication.getMessage("confirmation.url",
                    registrationRequest.getCode()));
            params.put("enter.code.page", prApplication.getMessage("enter.code.page"));

            params.put("registration.code", registrationRequest.getCode());
            new EmailFromTemplate("registration.request", Locale.ENGLISH, params)
                    .send(email);
        } catch (final NoSuchEmailTemplateException e) {
            logger.error(e);
        }

    }

    private String generateRegistrationCode() {
        String code = "";
        final Random random = new Random();
        for (int i = 0; i < DbConstants.RegistrationRequest.CODE_SIZE; i++) {
            code = code + (Math.abs(random.nextInt() % 10));
        }

        return code;
    }

}
